package com.weshare.config;

import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
import com.dangdang.ddframe.job.reg.base.CoordinatorRegistryCenter;
import com.weshare.job.FileBackupJobDb;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;


@Configuration
public class ElasticJobConfig {

    @Autowired
    //private SimpleJob fileBackupJob;
    private FileBackupJobDb fileBackupJobDb;

    @Autowired
    private CoordinatorRegistryCenter coordinatorRegistryCenter;


    @Bean(initMethod = "init")
    public SpringJobScheduler initSimpleElasticJob() {

        SpringJobScheduler springJobScheduler = new SpringJobScheduler(fileBackupJobDb, coordinatorRegistryCenter,
                createJobConfiguration(fileBackupJobDb.getClass(), "0/3 * * * * ?", 4, "0=text,1=image,2=radio,3=vedio"));
        return springJobScheduler;
    }

    private LiteJobConfiguration createJobConfiguration(final Class<? extends SimpleJob> jobClass,
                                                        final String corn,
                                                        final int shardingTotalCount,
                                                        final String shardingItemParameters) {
        JobCoreConfiguration.Builder builder = JobCoreConfiguration.newBuilder(jobClass.getName(), corn, shardingTotalCount);

        if (!StringUtils.isEmpty(shardingItemParameters)) {
            builder.shardingItemParameters(shardingItemParameters);
        }

        JobCoreConfiguration jobCoreConfiguration = builder.build();
        SimpleJobConfiguration simpleJobConfiguration = new SimpleJobConfiguration(jobCoreConfiguration, jobClass.getCanonicalName());
        LiteJobConfiguration liteJobConfiguration = LiteJobConfiguration.newBuilder(simpleJobConfiguration).overwrite(true).build();
        return liteJobConfiguration;
    }
}
